import time
import random
import pyautogui
import cv2
import numpy as np
from PIL import ImageGrab
import keyboard

# 置信度阈值设置 - 可分别调整1.png和2.png的阈值
THRESHOLD_1 = 0.8  # 1.png的识别阈值
THRESHOLD_2 = 0.8  # 2.png的识别阈值


def find_image_on_screen(target_path, screen_gray, threshold=0.8):
    """在指定灰度屏幕图像上查找目标图像，返回位置和最大置信度"""
    print(f"[DEBUG] 正在查找 {target_path}，使用置信度阈值: {threshold:.2f}")

    # 读取目标图像
    target = cv2.imread(target_path, 0)
    if target is None:
        print(f"[DEBUG] 无法读取图像文件: {target_path}")
        return [], 0.0

    # 模板匹配
    result = cv2.matchTemplate(screen_gray, target, cv2.TM_CCOEFF_NORMED)
    locations = np.where(result >= threshold)

    # 提取匹配位置和实际匹配分数
    positions = []
    scores = []
    h, w = target.shape[:2]

    # 获取所有匹配位置及其分数
    for y, x in zip(*locations):
        center_x = x + w // 2
        center_y = y + h // 2
        positions.append((center_x, center_y))
        scores.append(result[y, x])

    # 计算最大匹配分数
    max_score = float(np.max(result)) if result.size > 0 else 0.0

    # 输出匹配结果
    if positions:
        print(f"[DEBUG] 找到 {len(positions)} 个 {target_path} 匹配")
        for i, (pos, score) in enumerate(zip(positions, scores)):
            print(f"[DEBUG] 匹配 {i+1}: 位置 {pos}, 置信度 {score:.4f}")
        print(f"[DEBUG] {target_path} 最高置信度: {max_score:.4f}")
    else:
        print(f"[DEBUG] 未找到 {target_path} 匹配 (阈值 {threshold:.2f})")
        print(f"[DEBUG] {target_path} 最高置信度: {max_score:.4f} (低于阈值)")

    return positions, max_score


def toggle_running():
    """切换运行状态的回调函数"""
    global running
    running = not running
    status = "继续" if running else "暂停"
    print(f"\n[控制] 检测已{status}")


def main():
    global running
    running = False  # 控制是否运行检测

    # 注册F4热键
    keyboard.add_hotkey('f4', toggle_running, suppress=True)

    # 滚轮随机范围设置 (负数表示向下滚动)
    SCROLL_MIN = -150
    SCROLL_MAX = -50

    print("程序开始运行...")
    print("按Ctrl+C停止程序")
    print("按F4暂停/继续检测")
    print(f"1.png 置信度阈值: {THRESHOLD_1:.2f}")
    print(f"2.png 置信度阈值: {THRESHOLD_2:.2f}")
    print(f"滚轮随机范围: {SCROLL_MIN} 至 {SCROLL_MAX}")

    try:
        while True:
            if running:
                # 每0.5秒检查一次
                time.sleep(0.3)

                # 截取屏幕（一次截图用于两个图像的检测，确保同时性）
                screen = ImageGrab.grab()
                screen_np = np.array(screen)
                screen_gray = cv2.cvtColor(screen_np, cv2.COLOR_BGR2GRAY)

                # 同时检测1.png和2.png
                positions_1, max_score_1 = find_image_on_screen(
                    "1.png", screen_gray, THRESHOLD_1)
                positions_2, max_score_2 = find_image_on_screen(
                    "2.png", screen_gray, THRESHOLD_2)

                # 比较两者的置信度并执行相应操作
                print(
                    f"[DEBUG] 置信度比较: 1.png={max_score_1:.4f}, 2.png={max_score_2:.4f}")

                if max_score_2 > max_score_1 and max_score_2 >= THRESHOLD_2:
                    # 2.png置信度更高且超过阈值，按下F键
                    print(
                        f"[操作] 2.png置信度更高 ({max_score_2:.4f} > {max_score_1:.4f})，按下F键")
                    pyautogui.press('f')
                    time.sleep(6)

                elif max_score_1 >= max_score_2 and max_score_1 >= THRESHOLD_1:
                    # 1.png置信度更高或相等且超过阈值，向下滚动滚轮
                    scroll_amount = random.randint(SCROLL_MIN, SCROLL_MAX)
                    print(
                        f"[操作] 1.png置信度更高 ({max_score_1:.4f} >= {max_score_2:.4f})，向下滚动 {scroll_amount}")
                    pyautogui.scroll(scroll_amount)

                else:
                    # 两者都低于阈值，继续等待
                    print("[DEBUG] 两者均未达到阈值，继续等待...")

            else:
                # 暂停状态下减少CPU占用
                time.sleep(1)

    except KeyboardInterrupt:
        print("\n程序已停止")
    finally:
        keyboard.unhook_all_hotkeys()


if __name__ == "__main__":
    try:
        import keyboard
    except ImportError:
        print("请先安装keyboard库：pip install keyboard")
        exit(1)
    main()
